package service

import (
	"bytes"
	"context"
	"engine/cache"
	"errors"
	"fmt"
	"github.com/goccy/go-json"
	"io/ioutil"
	sferrors "lib/sf-errors"
	"net/http"
	"strings"
	"time"
)

type Yongjinlist struct {
	Errcode   int                     `json:"errcode"`
	Errmsg    string                  `json:"errmsg"`
	OrderList []*YongjinlistOrderList `json:"order_list"`
	HasMore   bool                    `json:"has_more"`
}

type YongjinlistOrderList struct {
	OrderId string `json:"order_id"`
	SkuId   string `json:"sku_id"`
}

type YongjinOrderDea struct {
	Errcode  int    `json:"errcode"`
	Errmsg   string `json:"errmsg"`
	BaseInfo struct {
		OrderId         string `json:"order_id"`
		SpuId           string `json:"spu_id"`
		SkuId           string `json:"sku_id"`
		SpecialId       string `json:"special_id"`
		OrderStatus     int    `json:"order_status"`
		ActualPayment   string `json:"actual_payment"`
		OrderCreateTime int    `json:"order_create_time"`
		OrderUpdateTime int    `json:"order_update_time"`
		BuyerInfo       struct {
			OpenId  string `json:"open_id"`
			UnionId string `json:"union_id"`
		} `json:"buyer_info"`
	} `json:"base_info"`
	CommissionInfo struct {
		State            int    `json:"state"`
		Ratio            string `json:"ratio"`
		ExpectSettleTime int    `json:"expect_settle_time"`
		ExpectSettlement string `json:"expect_settlement"`
	} `json:"commission_info"`
	ChannelInfo struct {
		ChannelType int `json:"channel_type"`
	} `json:"channel_info"`
	ProductInfo struct {
		Title    string `json:"title"`
		ThumbImg string `json:"thumb_img"`
	} `json:"product_info"`
}

type AccessTokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	Errcode     int    `json:"errcode,omitempty"`
	Errmsg      string `json:"errmsg,omitempty"`
}

const (
	DhuoAppID     = "wx77d3772ea81f3b81"
	DhuoAppSecret = "7af7507fb96c40196e97c3e5636e0980"
)

func GetWxDaiHuoAccessToken() (string, error) {
	ctx := context.Background()
	daihuoTokenKey := "daihuoTokenKey"
	accessToken, err := cache.RedisContextGet[string](ctx, daihuoTokenKey)
	if err == nil && accessToken != nil && *accessToken != "" {
		return *accessToken, nil
	}
	url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
		DhuoAppID, DhuoAppSecret)
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var result AccessTokenResponse
	err = json.Unmarshal(body, &result)
	if err != nil {
		return "", err
	}

	if result.Errcode != 0 {
		return "", fmt.Errorf("wechat error: %f, %s", result.Errcode, result.Errmsg)
	}

	tokenExpiry := time.Duration(result.ExpiresIn-500) * time.Second
	cache.RedisContextSet(ctx, daihuoTokenKey, result.AccessToken, tokenExpiry)

	return result.AccessToken, nil
}

func GetYongjinOrderDetail(orderID string) (string, bool, error) {
	type OrderListRequest struct {
		OrderID  string `json:"order_id,omitempty"`
		PageSize int    `json:"page_size,omitempty"`
	}

	accessToken, err := GetWxDaiHuoAccessToken()
	if err != nil {
		return "", false, err
	}
	url := fmt.Sprintf("https://api.weixin.qq.com/channels/ec/talent/get_order_list?access_token=%s", accessToken)
	req := OrderListRequest{
		OrderID:  orderID,
		PageSize: 5,
	}
	reqBody, err := json.Marshal(req)
	if err != nil {
		return "", false, err
	}

	resp, err := http.Post(url, "application/json", bytes.NewBuffer(reqBody))
	if err != nil {
		return "", false, err
	}
	defer resp.Body.Close()

	listResp, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", false, err
	}

	var yongjinlist Yongjinlist
	if err = json.Unmarshal(listResp, &yongjinlist); err != nil {
		return "", false, err
	}
	if yongjinlist.Errcode != 0 {
		return "", false, sferrors.NewStringf(yongjinlist.Errmsg)
	}
	if len(yongjinlist.OrderList) == 0 {
		return "", false, sferrors.NewStringf("没有找到该订单")
	}
	//查询佣金详情？
	isOk := false
	skuid := make([]string, 0, len(yongjinlist.OrderList))
	for _, i2 := range yongjinlist.OrderList {
		respEndDaa, err := GetYongjin(i2.OrderId, accessToken, i2.SkuId)
		if err == nil {
			if respEndDaa == true {
				isOk = true
				skuid = append(skuid, i2.SkuId)
			}
		}
	}
	return strings.Join(skuid, ","), isOk, nil
}

func GetYongjin(orderID, accessToken, skuId string) (bool, error) {
	url := fmt.Sprintf("https://api.weixin.qq.com/channels/ec/talent/get_order_detail?access_token=%s", accessToken)
	type orderDrayongjinReq struct {
		OrderId string `json:"order_id"`
		SkuId   string `json:"sku_id"`
	}

	req := orderDrayongjinReq{
		OrderId: orderID,
		SkuId:   skuId,
	}

	reqBody, err := json.Marshal(req)
	if err != nil {
		return false, err
	}

	resp, err := http.Post(url, "application/json", bytes.NewBuffer(reqBody))
	if err != nil {
		return false, err
	}
	defer resp.Body.Close()

	listResp, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return false, err
	}

	var yongjinOrderDea YongjinOrderDea
	if err = json.Unmarshal(listResp, &yongjinOrderDea); err != nil {
		return false, err
	}
	if yongjinOrderDea.Errcode != 0 {
		return false, errors.New(yongjinOrderDea.Errmsg)
	}
	if yongjinOrderDea.BaseInfo.OrderStatus == 10 || yongjinOrderDea.BaseInfo.OrderStatus == 7 || yongjinOrderDea.BaseInfo.OrderStatus == 8 || yongjinOrderDea.BaseInfo.OrderStatus == 1 {
		return false, sferrors.NewStringf("确定订单状态")
	}
	return true, nil
}
func GetYongjinDetai(accessToken, orderID, skuId string) (int, error) {
	url := fmt.Sprintf("https://api.weixin.qq.com/channels/ec/talent/get_order_detail?access_token=%s", accessToken)
	type orderDrayongjinReq struct {
		OrderId string `json:"order_id"`
		SkuId   string `json:"sku_id"`
	}

	req := orderDrayongjinReq{
		OrderId: orderID,
		SkuId:   skuId,
	}

	reqBody, err := json.Marshal(req)
	if err != nil {
		return 0, err
	}

	resp, err := http.Post(url, "application/json", bytes.NewBuffer(reqBody))
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()

	listResp, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, err
	}

	var yongjinOrderDea YongjinOrderDea
	if err = json.Unmarshal(listResp, &yongjinOrderDea); err != nil {
		return 0, err
	}
	if yongjinOrderDea.Errcode != 0 {
		return 0, errors.New(yongjinOrderDea.Errmsg)
	}
	if yongjinOrderDea.BaseInfo.OrderStatus == 10 || yongjinOrderDea.BaseInfo.OrderStatus == 7 || yongjinOrderDea.BaseInfo.OrderStatus == 8 || yongjinOrderDea.BaseInfo.OrderStatus == 1 {
		return 2, errors.New("确定订单状态")
	}
	if yongjinOrderDea.BaseInfo.OrderStatus == 6 || yongjinOrderDea.BaseInfo.OrderStatus == 9 {
		return 4, nil
	}
	return 1, nil
}
